package modelCollection;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import dataCollection.AbstractDetail;
import dataCollection.Trait;
import dataCollection.Tree;

public class XMLTraitsReader {
  
  private XMLTraitsReader(){}
  
  public static void readTraits(Tree<AbstractDetail> ability_tree) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      Document document = builder.parse( new File("bin/resources/traits_en.xml"));
      readDoc(document, ability_tree);
    } catch (ParserConfigurationException | SAXException | IOException e) {
      e.printStackTrace();
    }
  }
  
  private static void readDoc (Document doc, Tree<AbstractDetail> ability_tree) {
    NodeList entries = doc.getElementsByTagName("trait");
    for(int i = 0; i < entries.getLength(); ++i) {
      System.out.println("-");
      String trait_name = null;
      String trait_desc = null;
      boolean is_physical = false;
      Element node = (Element) entries.item(i);
      NamedNodeMap attributes = node.getAttributes(); 
      for(int j = 0; j < attributes.getLength(); ++j) {
        Attr attr =(Attr) attributes.item(j);
        if(attr.getNodeName().equals("id")) {
          trait_name = new String(attr.getNodeValue());
        }
      }
      
      NodeList children = node.getChildNodes();
      for(int k = 0; k < children.getLength(); ++k) {
        if(children.item(k).getNodeName().equals("description")) {
          trait_desc = new String(children.item(k).getTextContent());
        }
        if(children.item(k).getNodeName().equals("type")) {
          if(children.item(k).getTextContent().equals("Physical")) {
            is_physical = true;
          }
        }
      }
      
      // TODO FEHLERBEHANDLUNG
     Trait new_trait = new Trait(trait_name, trait_desc, is_physical);
     ability_tree.pushAndStay(new_trait);
    }
    System.out.println("======");

  }

}
